const fs = require('fs');
const path = require('path');

class SimpleDatabase {
    constructor() {
        this.dataDir = path.join(__dirname, 'data');
        this.usersFile = path.join(this.dataDir, 'users.json');
        this.gameDataFile = path.join(this.dataDir, 'gameData.json');
        this.gameRecordsFile = path.join(this.dataDir, 'gameRecords.json');
        
        // 确保数据目录存在
        if (!fs.existsSync(this.dataDir)) {
            fs.mkdirSync(this.dataDir, { recursive: true });
        }
        
        // 初始化数据文件
        this.initializeFiles();
    }
    
    initializeFiles() {
        // 初始化用户文件
        if (!fs.existsSync(this.usersFile)) {
            fs.writeFileSync(this.usersFile, JSON.stringify([], null, 2));
        }
        
        // 初始化游戏数据文件
        if (!fs.existsSync(this.gameDataFile)) {
            fs.writeFileSync(this.gameDataFile, JSON.stringify({}, null, 2));
        }
        
        // 初始化游戏记录文件
        if (!fs.existsSync(this.gameRecordsFile)) {
            fs.writeFileSync(this.gameRecordsFile, JSON.stringify([], null, 2));
        }
    }
    
    // 用户管理
    getAllUsers() {
        try {
            const data = fs.readFileSync(this.usersFile, 'utf8');
            return JSON.parse(data);
        } catch (error) {
            console.error('读取用户数据失败:', error);
            return [];
        }
    }
    
    getUser(username) {
        const users = this.getAllUsers();
        return users.find(user => user.username === username);
    }
    
    addUser(username, userData) {
        const users = this.getAllUsers();
        const existingUserIndex = users.findIndex(user => user.username === username);
        
        if (existingUserIndex !== -1) {
            users[existingUserIndex] = userData;
        } else {
            users.push(userData);
        }
        
        try {
            fs.writeFileSync(this.usersFile, JSON.stringify(users, null, 2));
            return true;
        } catch (error) {
            console.error('保存用户数据失败:', error);
            return false;
        }
    }
    
    updateUser(username, userData) {
        return this.addUser(username, userData);
    }
    
    deleteUser(username) {
        const users = this.getAllUsers();
        const filteredUsers = users.filter(user => user.username !== username);
        
        try {
            fs.writeFileSync(this.usersFile, JSON.stringify(filteredUsers, null, 2));
            
            // 同时删除用户的游戏数据
            const gameData = this.getAllGameData();
            const gameDataObj = Object.fromEntries(gameData);
            
            Object.keys(gameDataObj).forEach(key => {
                if (key.startsWith(username + '_')) {
                    delete gameDataObj[key];
                }
            });
            
            fs.writeFileSync(this.gameDataFile, JSON.stringify(gameDataObj, null, 2));
            
            return true;
        } catch (error) {
            console.error('删除用户失败:', error);
            return false;
        }
    }
    
    updateUserLogin(username) {
        const user = this.getUser(username);
        if (user) {
            user.lastLogin = new Date();
            this.updateUser(username, user);
        }
    }
    
    // 游戏数据管理
    getAllGameData() {
        try {
            const data = fs.readFileSync(this.gameDataFile, 'utf8');
            const gameDataObj = JSON.parse(data);
            return new Map(Object.entries(gameDataObj));
        } catch (error) {
            console.error('读取游戏数据失败:', error);
            return new Map();
        }
    }
    
    getGameData(key) {
        const gameData = this.getAllGameData();
        return gameData.get(key);
    }
    
    setGameData(key, data) {
        try {
            const gameData = this.getAllGameData();
            gameData.set(key, data);
            
            const gameDataObj = Object.fromEntries(gameData);
            fs.writeFileSync(this.gameDataFile, JSON.stringify(gameDataObj, null, 2));
            return true;
        } catch (error) {
            console.error('保存游戏数据失败:', error);
            return false;
        }
    }
    
    // 游戏记录管理
    getGameRecords(gameName = null) {
        try {
            const data = fs.readFileSync(this.gameRecordsFile, 'utf8');
            const records = JSON.parse(data);
            
            if (gameName) {
                return records.filter(record => record.gameName === gameName);
            }
            
            return records;
        } catch (error) {
            console.error('读取游戏记录失败:', error);
            return [];
        }
    }
    
    addGameRecord(username, gameName, recordData) {
        try {
            const records = this.getGameRecords();
            const newRecord = {
                id: Date.now() + Math.random(),
                username,
                gameName,
                ...recordData,
                createdAt: new Date()
            };
            
            records.push(newRecord);
            
            // 保持最近1000条记录
            if (records.length > 1000) {
                records.splice(0, records.length - 1000);
            }
            
            fs.writeFileSync(this.gameRecordsFile, JSON.stringify(records, null, 2));
            return true;
        } catch (error) {
            console.error('保存游戏记录失败:', error);
            return false;
        }
    }
    
    getTodayRecords() {
        const records = this.getGameRecords();
        const today = new Date().toDateString();
        
        return records.filter(record => 
            new Date(record.createdAt).toDateString() === today
        );
    }
    
    // 用户统计
    getUserStats(username) {
        const gameData = this.getAllGameData();
        const userStats = {};
        
        for (const [key, data] of gameData) {
            if (key.startsWith(username + '_')) {
                const gameName = key.split('_')[1];
                userStats[gameName] = {
                    totalGames: data.gamesPlayed || 0,
                    highScore: data.highScore || 0,
                    lastPlayed: data.updatedAt || null
                };
            }
        }
        
        return userStats;
    }
}

module.exports = SimpleDatabase;